<template>
	<div class="news-wrap">
		<c_header :title="$title" :leftOptions="{showBack: false}" :rightOptions="{showMore: true}"></c_header>
		<div class="news-nav">
			<tab class="news-nav-tab" :line-width=2 active-color='#e22f0c' bar-active-color="#e22f0c" v-model="indexs">
	    		<tab-item class="vux-center" :selected="indexs === index" v-for="(item, index) in news" @click="indexs = index" :key="index">{{item.cname}}</tab-item>
		    </tab>
		</div>
		<div class="update-tips fs-smaller" v-if="updateTips"><div @click="closeUpdateTips">{{updateTime/60000}}分钟后将会有新的资讯<icon type="clear"></icon></div></div>
	    <swiper v-model="indexs" :show-dots="false" :threshold="200" :min-moving-distance="150">
	    	<swiper-item v-for="(tab, index) in news" :key="index">
	    		<div class="news-list">
		    		<div class="update-tips fs-smaller" v-show="tab.update"><div @click="getNewsFromNetwork()">您有新的资讯，点击加载<badge></badge></div></div>
		    		<div class="error" v-if="tab.error">网络连接失败，请刷新网页重试</div>
		    		<ul v-else>
				    	<li v-for="item in tab.data">
				    		<router-link :to="{name:'article', query: {title:item.title, url: $base64.encode(item.url)}}">
				    			<div class="news-normal" v-if="item.thumbnail_pic_s02">
				    				<h2 class="clamp">{{item.title}}</h2>
					    			<div class="news-image">
					    				<div><img :src="item.thumbnail_pic_s"></div>
					    				<div><img v-if="item.thumbnail_pic_s02" :src="item.thumbnail_pic_s02"></div>
					    				<div><img v-if="item.thumbnail_pic_s03" :src="item.thumbnail_pic_s03"></div>
					    			</div>
					    			<p class="news-resource fs-smaller">来源：{{item.author_name + ' ' + item.date}}</p>
				    			</div>
				    			<div class="news-simple" v-else>
				    				<div><img :src="item.thumbnail_pic_s"></div>
				    				<div>
				    					<h2 class="clamp">{{item.title}}</h2>
				    					<p class="news-resource fs-smaller">来源：{{item.author_name + ' ' + item.date}}</p>
				    				</div>
				    			</div>
				    		</router-link>
				    	</li>
				    </ul>
			    </div>
	    	</swiper-item>
	    </swiper>
	    <c_sidemenu></c_sidemenu>
	</div>
</template>

<script>
import c_header from '@/components/c_header'
import c_sidemenu from '@/components/c_sidemenu'
import { Tab, TabItem, Swiper, SwiperItem, Icon, Badge } from 'vux'

export default {
	name: 'news',
	data () {
		return {
			listLoading: false,
			news: [
				{
					type: 'hot',
					cname: '头条',
					data:[],
					error: false,
					update: false
				}, 
				{
					type: 'shehui',
					cname: '社会',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'guonei',
					cname: '国内',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'guoji',
					cname: '国际',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'yule',
					cname: '娱乐',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'tiyu',
					cname: '体育',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'junshi',
					cname: '军事',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'keji',
					cname: '科技',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'caijing',
					cname: '财经',
					data: [],
					error: false,
					update: false
				}, 
				{
					type: 'shishang',
					cname: '时尚',
					data: [],
					error: false,
					update: false
				}
			],
			indexs: 0,
			updateTips: false,
			updateTime: 600000
		}
	},
	components: {
		c_header, c_sidemenu, Tab, TabItem, Swiper, SwiperItem, Icon, Badge
	},
	methods: {
		getNews (type) {
			//如果本地没有数据，则从远程获取
			this.getNewsFromLocal() || this.getNewsFromNetwork()
		},
		getNewsFromNetwork () {
			console.log('data from local')
			this.$vux.loading.show({text: '数据加载中...'})
			this.$getData.news({type: this.currentNews.type}, this.getNewsSuccess, this.getNewsError)
		},
		getNewsFromLocal () {
			console.log('data from network')
			let localData = localStorage[this.currentNews.type]
			if(localData && !this.currentNews.update){
				localData = JSON.parse(localData)
				this.currentNews.data = localData.data
				//离可以跟新还有多少时间/当前时间-上次跟新时间-跟新间隔时间
				let lastTime = +new Date() - localData.updateTime - this.updateTime
				if(lastTime >= 0){
					//时间到了，提示可以跟新
					this.currentNews.update = true
				}else{
					//时间没到，指定时间提示跟新
					setTimeout(() => {this.currentNews.update = true}, -lastTime)
				}
				//必须异步设置swiper高度，否则获取不到高度
				setTimeout(this.setSwiperHeight, 0)
				return true
			}
			return false
		},
		getNewsSuccess (response) {
			this.currentNews.error = false
			let localData = localStorage[this.currentNews.type]
			if(localData){
				localData = JSON.parse(localData)
				if(JSON.stringify(localData.data) != JSON.stringify(response.data.result.data)){
					this.currentNews.data = response.data.result.data.concat(this.currentNews.data)
				}
			}else{
				this.currentNews.data = response.data.result.data
			}
			//历史新闻数据存到本地
			localStorage.setItem(
				this.currentNews.type,
				JSON.stringify({updateTime: +new Date(), data: this.currentNews.data})
			)
			//设定计时器，指定时间提示跟新
			this.currentNews.update = false
			setTimeout(() => {
				this.currentNews.update = true
			}, this.updateTime)
			this.$vux.loading.hide()
			this.setSwiperHeight()
		},
		getNewsError () {
			this.$vux.loading.hide()
			if(this.currentNews.data.length){
				this.$vux.toast.text("网络连接失败", 2000)
			}else{
				this.currentNews.error = true
			}
		},
		setNavScrollWidth () {
			let tabWidth = 0;
			let tab = document.querySelector('.news-nav-tab')
			let tabItem = tab.querySelectorAll('.vux-tab-item');
			for(let i = 0;i<tabItem.length;i++){
				tabWidth += window.getComputedStyle(tabItem[i], null).width.replace('px', '')*1
			}
			tab.style['min-width'] = tabWidth + 'px'
		},
		setSwiperHeight () {
			this.$nextTick(() => {
				document.body.scrollTop = 0
				document.querySelector('.vux-swiper').style.height = window.getComputedStyle(document.querySelectorAll('.news-list')[this.indexs], null).height
			})
		},
		closeUpdateTips () {
			this.updateTips = false
			localStorage.setItem('updateTips', this.updateTips)
		}
	},
	computed: {
		currentNews () {
			return this.news[this.indexs]
		}
	},
	watch: {
		indexs (index) {
			document.querySelectorAll(".news-nav-tab>div")[index].scrollIntoView();
			this.news[index].data.length || this.getNews(this.news[index].type)
		}
	},
	mounted () {
		document.title = this.$title
		this.setNavScrollWidth()
		this.getNews(this.currentNews.type)
		//本地没有记录，应该是用户第一次打开，显示跟新提示
		if(localStorage.updateTips == undefined && !this.currentNews.update) {
			this.updateTips = true
		}
	},
	activated () {
		document.title = this.$title
	}
}
</script>

<style>
	.news-wrap:before{content: '';display: block;height: 44px;}
	.news-nav{position: fixed;left: 0;top: 44px;right: 0;z-index: 1;overflow-x: scroll;-webkit-overflow-scrolling: touch;}
	::-webkit-scrollbar{display: none;}
	.vux-tab .vux-tab-item{min-width: 50px;}
	
	.news-list{padding: 0 .8rem;}
	.news-list li:last-child a{border-bottom: none;}
	.news-list a{display: block;padding: .6rem 0 .46rem;border-bottom: 1px solid #ececec;}
	.news-list h2{font-weight: normal;line-height: 20px;}
	.news-image{display: flex;justify-content:space-between;margin-top: .5rem;}
	.news-image div{width: 33%;position: relative;}
	.news-image div:nth-child(2){margin: 0 .25rem;}
	.news-image div:after, .news-simple div:first-child:after{content: '';display: block;padding-top: 75%;}
	.news-image img, .news-simple div:first-child img{position: absolute;width: 100%;}
	.news-resource{margin-top: .3rem; color: #c5c5c5;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}
	
	.news-simple{display: flex;}
	.news-simple div:first-child{width: 4.5rem;margin-right: .6rem;position: relative;}
	.news-simple div:last-child{width: 12.5rem;overflow: hidden;}
	.news-simple h2{height: 40px;margin-top: .18rem;}
	
	.update-tips{text-align: center;padding-top: .6rem;}
	.update-tips>div{display: inline-block;border: 1px solid #ccc;border-radius: 5px;padding: 4px 6px;background: #fff;}
	.update-tips>div span{margin: -3px 0 0 4px;}
	.update-tips>div i{margin: -2px 0 0 4px;}
</style>